package com.local.publisher.controller;

import com.local.publisher.pojo.Order;
import com.local.publisher.service.OrderService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${rabbitmqs.order-exchange}")
    private String orderExchange;

    @Value("${rabbitmqs.order-queue-routing-key}")
    private String orderQueueRoutingKey;

    @GetMapping("/{orderId}")
    @ResponseBody
    public String index(@PathVariable("orderId") Integer orderId) {
        return "orderId:"+orderId;
    }

    @PostMapping
    @ResponseBody
    public String save(Order order) {
        Long time =  (new Date().getTime()) /1000;
        String timeString = time.toString();
        int timeInteger = Integer.parseInt(timeString);
        order.setCreateTime(timeInteger);
        order.setUpdateTime(timeInteger);

        Integer saveResult = orderService.save(order);
        if (saveResult > 0) {
            Integer orderId = order.getOrderId();
            rabbitTemplate.convertAndSend(this.orderExchange, this.orderQueueRoutingKey, orderId, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    //超过30分钟未支付的订单，将其状态更新完为“删除”
                    //设置消息的有效时间30分钟，过期则自动进入dead letter死信消息队列。监听者Listener会监听死信消息队列，获取死信消息，将orderId对应的订单状态更新为“已删除”
                    //message.getMessageProperties().setExpiration("1800000");//30分钟过期
                    message.getMessageProperties().setExpiration("30000");//测试，30秒过期
                    return message;
                }
            });
            return "订单新增成功，OrderId："+orderId;
        } else {
            return "订单新增失败";
        }
    }
}
